//
//  JYTakeVideo.m
//  NRT
//
//  Created by JY on 15/9/14.
//  Copyright (c) 2015年 JY. All rights reserved.
//

#import "JYTakeVideo.h"
#import <MediaPlayer/MediaPlayer.h>
#import "JYPlayVideo.h"
#import "SVProgressHUD.h"
#import "SandBox.h"
#import "UIButton+DJBlock.h"
#import "DJCameraManager.h"
#import "Remind.h"
#import "typeValue.h"
#import "MZTimerLabel.h"
#import "TAlertView.h"
#define WS(weakSelf)  __weak __typeof(&*self)weakSelf = self;
#define AppWidth [[UIScreen mainScreen] bounds].size.width
#define AppHeigt [[UIScreen mainScreen] bounds].size.height
#define MAX_VIDEO_DUR    600
#define COUNT_DUR_TIMER_INTERVAL  0.025
#define VIDEO_FOLDER    @"videos"


@interface JYTakeVideo ()
{
    
    NSURL *_finashURL;
    UIButton *_sureBtn;
    MPMoviePlayerController *_player;
    float   _float_totalDur;
    float   _float_currentDur;
    BOOL on ;
    BOOL NOU;
}
@property(nonatomic,strong)AVCaptureSession      *captureSession;
@property(nonatomic,strong)AVCaptureDeviceInput  *videoDeviceInput;
@property(nonatomic,strong)AVCaptureMovieFileOutput *movieFileOutput;
@property(nonatomic,strong)AVCaptureVideoPreviewLayer *preViewLayer;
@property(nonatomic,strong)UIView          *preview;
@property(nonatomic,strong)UIProgressView  *progressView;
@property(nonatomic,strong)NSTimer     *timer;
@property(nonatomic,strong)NSMutableArray     *files;
@property(nonatomic,strong)UIButton *button;
@property(nonatomic,strong)MZTimerLabel *timeLabel;
@property(nonatomic,strong)UILabel *label;
@property(nonatomic,unsafe_unretained)BOOL      isCameraSupported;
@property(nonatomic,unsafe_unretained)BOOL      isTorchSupported;
@property(nonatomic,unsafe_unretained)BOOL      isFrontCameraSupported;
@property(nonatomic,assign)int *number;

@end

@implementation JYTakeVideo
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor blackColor];
   
    self.automaticallyAdjustsScrollViewInsets = NO;
    on = NO;
    NOU = NO;
    //创建视频存储目录
    [[self class] createVideoFolderIfNotExist];
    //用来存储视频路径 以便合成时使用
    self.files=[NSMutableArray array];
    //创建视频捕捉窗口
    [self initCapture];
    //创建录像按钮
    [self initRecordButton];
    
    [self initTitle];
    
    
}

- (void)initTitle{
      typeValue *type = [typeValue TimeTypeValue];
    if ([type.timeType isEqualToString:@"affection"] != 0)
    {
        self.navigationController.title = @"亲情";
        
    }else if ([type.timeType isEqualToString:@"friend"] != 0)
    {
         self.navigationController.title = @"友情";
        
    }else if([type.timeType isEqualToString:@"LOVE"] != 0)
    {
         self.navigationController.title = @"爱情";
        
    }else if([type.timeType isEqualToString:@"my"] != 0)
    {
        
        self.navigationController.title = @"送自己";
        
        
    }






}




-(void)initCapture
{
    self.captureSession = [[AVCaptureSession alloc]init];
    [_captureSession setSessionPreset:AVCaptureSessionPresetLow];
    
    
    AVCaptureDevice *frontCamera = nil;
    AVCaptureDevice *backCamera = nil;
    NSArray *cameras = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *camera in cameras) {
        if (camera.position == AVCaptureDevicePositionFront) {
            frontCamera = camera;
        } else {
            backCamera = camera;
        }
    }
    
    if (!backCamera) {
        self.isCameraSupported = NO;
        return;
    } else {
        self.isCameraSupported = YES;
        
        if ([backCamera hasTorch]) {
            self.isTorchSupported = YES;
        } else {
            self.isTorchSupported = NO;
        }
    }
    
    if (!frontCamera) {
        self.isFrontCameraSupported = NO;
    } else {
        self.isFrontCameraSupported = YES;
    }
    
    
    [backCamera lockForConfiguration:nil];
    if ([backCamera isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure]) {
        [backCamera setExposureMode:AVCaptureExposureModeContinuousAutoExposure];
    }
    
    [backCamera unlockForConfiguration];
    
    self.videoDeviceInput =  [AVCaptureDeviceInput deviceInputWithDevice:backCamera error:nil];
    
    AVCaptureDeviceInput *audioDeviceInput =[AVCaptureDeviceInput deviceInputWithDevice:[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio] error:nil];
    
    [_captureSession addInput:_videoDeviceInput];
    [_captureSession addInput:audioDeviceInput];
    
    
    //output
    self.movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
    [_captureSession addOutput:_movieFileOutput];
    
    //preset
    _captureSession.sessionPreset = AVCaptureSessionPresetHigh;
    
    //preview layer------------------
    self.preViewLayer = [AVCaptureVideoPreviewLayer layerWithSession:_captureSession];
    _preViewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    
    [_captureSession startRunning];
    
    
    
    self.preview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, AppWidth, AppHeigt - 100)];
     _preview.clipsToBounds = YES;
    [self.view addSubview:self.preview];
    
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, AppWidth, AppHeigt - 100)];
    CGAffineTransform transform = CGAffineTransformMakeScale(1.0f, 2.0f);
    self.progressView.transform = transform;
    self.progressView.progress=0;
    self.progressView.tintColor = [UIColor greenColor];
    self.progressView.trackTintColor = [UIColor blueColor];
    [self.preview addSubview:self.progressView];
    
    
    self.preViewLayer.frame = CGRectMake(0, 0, AppWidth, AppHeigt - 100 );
    [self.preview.layer addSublayer:self.preViewLayer];
    
    
}



-(void)initRecordButton
{
   
    //闪关灯设置
    static  CGFloat buttonW = 40;
    UIButton *lightBtn = [self buildButton:CGRectMake(5, AppHeigt - 100, buttonW, buttonW) normalimgStr:@"flashing_off.png" highlightImgSrt:@"flashing_on.png" selectedImgStr:@"" parentView:self.view];
   // [lightBtn addTarget:self action:@selector(switchFlashMode:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    [lightBtn addTarget:self action:@selector(lightBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view  addSubview:lightBtn];
    
    
    
    
    //摄像头前后调节
    
    UIButton *cameraBtn  = [self buildButton:CGRectMake(50, AppHeigt - 100, buttonW, buttonW) normalimgStr:@"switch_camera.png" highlightImgSrt:@"" selectedImgStr:@"" parentView:self.view];
    [cameraBtn addTarget:self action:@selector(cameraBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cameraBtn];
    
    
    //开始录制
    CGFloat buttonZ = 80;
   self.button = [self buildButton:CGRectMake((AppWidth  - 80) /2,AppHeigt - 90 , buttonZ, buttonZ) normalimgStr:@"shot.png" highlightImgSrt:@"shot_h.png" selectedImgStr:@"" parentView:self.view];
    [self.button addTarget:self action:@selector(touchUp) forControlEvents:UIControlEventTouchUpInside];
    [self.button addTarget:self action:@selector(ClickTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.button];
    
    //计时器
    UILabel *Label = [[UILabel alloc] initWithFrame:CGRectMake(self.view.bounds.origin.x + 10 ,AppHeigt - 50 , 150 , 40)];
    self.timeLabel = [[MZTimerLabel alloc] initWithLabel:Label andTimerType:MZTimerLabelTypeTimer];
    typeValue *type = [typeValue TimeTypeValue];
    if ([type.timeType isEqualToString:@"affection"] != 0)
    {
        
         [self.timeLabel setCountDownTime:60 * 4];
        
    }else if ([type.timeType isEqualToString:@"friend"] != 0)
    {
         [self.timeLabel setCountDownTime:60 * 4];
    
    }else if([type.timeType isEqualToString:@"LOVE"] != 0)
    {
       
    
            [self.timeLabel setCountDownTime:5 * 60];

    
    }else if([type.timeType isEqualToString:@"my"] != 0)
    {
      
        [self.timeLabel setCountDownTime:60 * 3];
    
    
    }

    self.timeLabel.resetTimerAfterFinish = YES;
    self.timeLabel.timeFormat = @"mm:ss";
    self.timeLabel.textAlignment = NSTextAlignmentCenter;
    self.timeLabel.timeLabel.font = [UIFont systemFontOfSize:28.0f];
    self.timeLabel.timeLabel.textColor =  [UIColor colorWithRed:0.609 green:0.960 blue:1.000 alpha:1.000];
    [self.view addSubview:Label];


    
    
    
    
    
    
    //完成录制
    _sureBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    _sureBtn.center = CGPointMake(300, 600);
    _sureBtn.bounds = CGRectMake(0, 0, 80, 60);
    [_sureBtn setTitle:@"点击保存"  forState:UIControlStateNormal];
    _sureBtn.userInteractionEnabled = NO;
    [_sureBtn addTarget:self action:@selector(sureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    _sureBtn.hidden = YES;
    [self.view addSubview:_sureBtn];
 
    
    
    

   
    
    
    
    
    
    

    
}
-(void)play
{
    JYPlayVideo *playVideoVC=[[JYPlayVideo alloc]init];
    playVideoVC.fileURL=_finashURL;
    [self.navigationController pushViewController:playVideoVC animated:YES];
}

#pragma mark - BtnClick

-(void)touchUp
{
    if (NOU  == NO) {
        NSURL *fileURL = [NSURL fileURLWithPath:[[self class] getVideoSaveFilePathString]];
        [self.files addObject:fileURL];
        //暂停计时器
         typeValue *type = [typeValue TimeTypeValue];
        if([type.timeType isEqualToString:@"Love"] != 0)
        {
            //第一次执行方法
            [self.timeLabel startWithEndingBlock:^(NSTimeInterval countTime) {
                if (countTime ) {
                    [self startCountDurTimer];
                }
                
                if (type.number == 0) {
                    NSString *people = [NSString stringWithFormat:@"好啦 好啦你的独白时间已经到啦 去吧--宝宝请来吧"];
                      TAlertView *alert = [[TAlertView alloc] initWithTitle:@"时间到" message:people buttons:@[@"本宝宝来啦"] andCallBack:^(TAlertView *alertView, NSInteger buttonIndex) {
                   [self  touchUp];
                   [self ClickTouch:self.button];
                   self.timeLabel.timeFormat = @"mm:ss";
                    self.timeLabel.timeLabel.textColor =  [UIColor colorWithRed:0.609 green:0.960 blue:1.000 alpha:1.000];
                   //调用储存
                  [self performSelector:@selector(sureBtnClick) withObject:nil afterDelay:0.5f];
                   typeValue *type =[typeValue TimeTypeValue];
                   type.number = type.number + 1;
               }];
               alert.style = TAlertViewStyleError;
               alert.tapToClose = NO;
              [alert show];
                    
                }
             //第二次执行的方法
                if (type.number == 1) {
                    
                    NSString *people  = [NSString stringWithFormat:@"快去把----叫来吧接下来的时间是你们两个一起的"];
                    TAlertView *alert = [[TAlertView alloc] initWithTitle:@"时间到" message:people buttons:@[@"确定"] andCallBack:^(TAlertView *alertView, NSInteger buttonIndex) {
                        [self  touchUp];
                        [self ClickTouch:self.button];
                        self.timeLabel.timeFormat = @"mm:ss";
                         self.timeLabel.timeLabel.textColor =  [UIColor colorWithRed:0.609 green:0.960 blue:1.000 alpha:1.000];
                        [self.timeLabel setCountDownTime:60*7];
                        //调用储存
                        [self performSelector:@selector(sureBtnClick) withObject:nil afterDelay:0.5f];
                        typeValue *type =[typeValue TimeTypeValue];
                        type.number = type.number + 1;
                        
                    }];
                    alert.style = TAlertViewStyleError;
                    alert.tapToClose = NO;
                    [alert show];
 
                }else
                {
                    
                  
                    [self.timeLabel startWithEndingBlock:^(NSTimeInterval countTime) {
                        TAlertView *alert = [[TAlertView alloc] initWithTitle:@"录制完成" message:@"您的时光囊已经制作完成" buttons:@[@"确定"] andCallBack:^(TAlertView *alertView, NSInteger buttonIndex)
                                             {
                                                 [self  touchUp];
                                                 type.number = 0;
                                                 [self performSelector:@selector(sureBtnClick) withObject:nil afterDelay:0.5f];
                                                 
                                             }];
                        alert.style = TAlertViewStyleError;
                        alert.tapToClose = NO;
                        [alert show];
                    }];

    
                }
                

             
            }];
            
        }else
        {
            [self.timeLabel startWithEndingBlock:^(NSTimeInterval countTime) {
                   TAlertView *alert = [[TAlertView alloc] initWithTitle:@"录制完成" message:@"您的时光囊已经制作完成" buttons:@[@"确定"] andCallBack:^(TAlertView *alertView, NSInteger buttonIndex)
                   {
                       [self  touchUp];
                       type.number = 0;
                       [self performSelector:@selector(sureBtnClick) withObject:nil afterDelay:0.5f];
                       
                   }];
                alert.style = TAlertViewStyleError;
                alert.tapToClose = NO;
                [alert show];
               }];

        }
        [_movieFileOutput startRecordingToOutputFileURL:fileURL recordingDelegate:self];
        NOU = YES;
    }else
    {
        [_movieFileOutput stopRecording];
        //暂停时间加载
        [self stopCountDurTimer];
        //暂停计时器
        [self.timeLabel pause];
        NOU = NO;
    }

    
}








//存储设置
-(void)sureBtnClick
{

    
    
    [SVProgressHUD showWithStatus:@"装箱中请勿关闭"];
    [_movieFileOutput stopRecording];
    [self stopCountDurTimer];
    [self mergeAndExportVideosAtFileURLs:self.files];
 
}
-(void)ClickTouch:(UIButton *)sender
{
    NSString *image = @"";
    if (on == NO) {
        on = YES;
        image = @"shot_h.png";
    }else
    {
        on = NO;
        image = @"shot.png";
    }
    [sender setImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
 
}
-(void)lightBtn:(UIButton *)sender
{
   
    NSString * image = @"";
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (![device hasTorch]) {
        NSLog(@"no torch");
    }else{
        [device lockForConfiguration:nil];
        if (on == NO ) {
            [device setTorchMode: AVCaptureTorchModeOn];
            on = YES;
            image = @"flashing_on.png";
        }
        else
        {
            [device setTorchMode: AVCaptureTorchModeOff];
            on = NO;
            image = @"flashing_off.png";
        }
        [sender setImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
        
        
        
        [device unlockForConfiguration];
    }

    
}


-(void)cameraBtn
{
  
    NSArray *inputs = self.captureSession.inputs;
    
    for ( AVCaptureDeviceInput *input in inputs )
    {
        AVCaptureDevice *device = input.device;
        
        if ( [device hasMediaType:AVMediaTypeVideo] )
        {
            AVCaptureDevicePosition position = device.position;
            AVCaptureDevice *newCamera = nil;
            AVCaptureDeviceInput *newInput = nil;
            
            if (position == AVCaptureDevicePositionFront)
            {
                newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
            }
            else{
                newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
            }
            newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
            
           
            [self.captureSession  beginConfiguration];
            [self.captureSession  removeInput:input];
            [self.captureSession  addInput:newInput];
            [self.captureSession  commitConfiguration];
            break;
        }
    }
  
}
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position
{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for ( AVCaptureDevice *device in devices )
        if ( device.position == position )
            return device;
    return nil;
}
-(void)cancelBtnClick
{

    [self.navigationController popViewControllerAnimated:YES];
}
-(void)backBtn
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - 获取视频大小及时长

//此方法可以获取文件的大小，返回的是单位是KB。
- (CGFloat) getFileSize:(NSString *)path
{
    NSFileManager *fileManager = [[NSFileManager alloc] init] ;
    float filesize = -1.0;
    if ([fileManager fileExistsAtPath:path])
    {
        NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];//获取文件的属性
        unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
        filesize = 1.0*size/1024;
    }
    return filesize;
}
//此方法可以获取视频文件的时长
- (CGFloat) getVideoLength:(NSURL *)URL
{
    NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:URL options:opts];
    float second = 0;
    second = urlAsset.duration.value/urlAsset.duration.timescale;
    return second;
}

#pragma mark - 创建视频目录及文件
//创建文件目录
+ (NSString *)getVideoSaveFilePathString
{
    
    NSString *path =[NSString stringWithFormat:@"%@/tmp/",NSHomeDirectory()];
    
    path = [path stringByAppendingPathComponent:VIDEO_FOLDER];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    formatter.dateFormat = @"yyyyMMddHHmmss";
    
    NSString *nowTimeStr = [formatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:0]];
    
    NSString *fileName = [[path stringByAppendingPathComponent:nowTimeStr] stringByAppendingString:@".mp4"];
    
    return fileName;
    
}

+ (BOOL)createVideoFolderIfNotExist
{
    ///NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    //获取本地文件路径
    NSString *path =[NSString stringWithFormat:@"%@/tmp/",NSHomeDirectory()];
    
    //[paths objectAtIndex:0];
    
    NSString *folderPath = [path stringByAppendingPathComponent:VIDEO_FOLDER];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = FALSE;
    BOOL isDirExist = [fileManager fileExistsAtPath:folderPath isDirectory:&isDir];
    
    if(!(isDirExist && isDir))
    {
        BOOL bCreateDir = [fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
        if(!bCreateDir){
            NSLog(@"创建图片文件夹失败");
            return NO;
        }
        return YES;
    }
    return YES;
}


#pragma mark - 合成文件
- (void)mergeAndExportVideosAtFileURLs:(NSArray *)fileURLArray
{
    NSError *error = nil;
    
    CGSize renderSize = CGSizeMake(0, 0);
    
    NSMutableArray *layerInstructionArray = [[NSMutableArray alloc] init];
    
    AVMutableComposition *mixComposition = [[AVMutableComposition alloc] init];
    
    CMTime totalDuration = kCMTimeZero;
    
    //先去assetTrack 也为了取renderSize
    NSMutableArray *assetTrackArray = [[NSMutableArray alloc] init];
    NSMutableArray *assetArray = [[NSMutableArray alloc] init];
    
    
    for (NSURL *fileURL in fileURLArray)
    {
        
        AVAsset *asset = [AVAsset assetWithURL:fileURL];
        
        if (!asset) {
            continue;
        }
        NSLog(@"%@---%@",asset.tracks,[asset tracksWithMediaType:@"vide"]);
        
        [assetArray addObject:asset];
        
        
        AVAssetTrack *assetTrack = [[asset tracksWithMediaType:@"vide"] objectAtIndex:0];
        
        [assetTrackArray addObject:assetTrack];
        
        renderSize.width = MAX(renderSize.width, assetTrack.naturalSize.height);
        renderSize.height = MAX(renderSize.height, assetTrack.naturalSize.width);
    }
    
    
    CGFloat renderW = MIN(renderSize.width, renderSize.height);
    
    for (int i = 0; i < [assetArray count] && i < [assetTrackArray count]; i++) {
        
        AVAsset *asset = [assetArray objectAtIndex:i];
        AVAssetTrack *assetTrack = [assetTrackArray objectAtIndex:i];
        
        AVMutableCompositionTrack *audioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
        
      
        [audioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, asset.duration) ofTrack:([[asset tracksWithMediaType:AVMediaTypeAudio] count]>0)?[[asset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0]:nil atTime:totalDuration error:nil];
        
        AVMutableCompositionTrack *videoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
        
        [videoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, asset.duration)
                            ofTrack:assetTrack
                             atTime:totalDuration
                              error:&error];
        
        //fix orientationissue
        AVMutableVideoCompositionLayerInstruction *layerInstruciton = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoTrack];
        
        totalDuration = CMTimeAdd(totalDuration, asset.duration);
        
        CGFloat rate;
        rate = renderW / MIN(assetTrack.naturalSize.width, assetTrack.naturalSize.height);
        
        CGAffineTransform layerTransform = CGAffineTransformMake(assetTrack.preferredTransform.a, assetTrack.preferredTransform.b, assetTrack.preferredTransform.c, assetTrack.preferredTransform.d, assetTrack.preferredTransform.tx * rate, assetTrack.preferredTransform.ty * rate);
        layerTransform = CGAffineTransformConcat(layerTransform, CGAffineTransformMake(1, 0, 0, 1, 0, -(assetTrack.naturalSize.width - assetTrack.naturalSize.height) / 2.0));//向上移动取中部影响
        layerTransform = CGAffineTransformScale(layerTransform, rate, rate);//放缩，解决前后摄像结果大小不对称
        
        [layerInstruciton setTransform:layerTransform atTime:kCMTimeZero];
        [layerInstruciton setOpacity:0.0 atTime:totalDuration];
        
        //data
        [layerInstructionArray addObject:layerInstruciton];
    }
    
    //get save path
    NSString *filePath = [[self class] getVideoMergeFilePathString];
    
    NSURL *mergeFileURL = [NSURL fileURLWithPath:filePath];
    
    //export
    AVMutableVideoCompositionInstruction *mainInstruciton = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
    mainInstruciton.timeRange = CMTimeRangeMake(kCMTimeZero, totalDuration);
    mainInstruciton.layerInstructions = layerInstructionArray;
    AVMutableVideoComposition *mainCompositionInst = [AVMutableVideoComposition videoComposition];
    mainCompositionInst.instructions = @[mainInstruciton];
    mainCompositionInst.frameDuration = CMTimeMake(1, 30);
    mainCompositionInst.renderSize = CGSizeMake(renderW, renderW);
    
    AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetMediumQuality];
    exporter.videoComposition = mainCompositionInst;
    exporter.outputURL = mergeFileURL;
    exporter.outputFileType = AVFileTypeMPEG4;
    exporter.shouldOptimizeForNetworkUse = YES;
    
    [exporter exportAsynchronouslyWithCompletionHandler:^{
       dispatch_async(dispatch_get_main_queue(), ^{
            
            _finashURL=mergeFileURL;
            [SVProgressHUD dismiss];
            [self play];
           //保存到相册
           // UISaveVideoAtPathToSavedPhotosAlbum(filePath, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
      
             //           if ([_delegate respondsToSelector:@selector(videoRecorder:didFinishMergingVideosToOutPutFileAtURL:)]) {
            //                [_delegate videoRecorder:self didFinishMergingVideosToOutPutFileAtURL:mergeFileURL];
            //            }
        });
      
    }];
}

+ (NSString *)getVideoMergeFilePathString
{
   // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *path =[NSString stringWithFormat:@"%@/tmp/",NSHomeDirectory()];
    // [paths objectAtIndex:0];
    
    path = [path stringByAppendingPathComponent:VIDEO_FOLDER];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    
    NSString *nowTimeStr = [formatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:0]];
    
    
    //后面修改视频的名字
    NSString *fileName = [[path stringByAppendingPathComponent:nowTimeStr] stringByAppendingString:@"merge.mp4"];
    
    return fileName;
}
#pragma mark - 计时器操作
 
- (void)startCountDurTimer
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:COUNT_DUR_TIMER_INTERVAL target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];

}
//进度条数值
- (void)onTimer:(NSTimer *)timer
{
    
    
//    self.timeLabel.timeLabel.textColor = [UIColor colorWithRed:arc4random()%255/256.0 green:arc4random()%255/256.0 blue:arc4random()%255/256.0 alpha:arc4random()%255/256.0];
    
    
    
   _sureBtn.userInteractionEnabled = YES;
   [_sureBtn setTitle:@"可以点了"  forState:UIControlStateNormal];
    if ([self.timeLabel.timeLabel.text isEqualToString:@"01:00"] != 0) {
     
     // self.timeLabel.timeLabel.textColor = [UIColor brownColor];
        self.timeLabel.timeFormat = @"mm:ss SS";
 
    }
    

    
   
   
 
    typeValue *type = [typeValue TimeTypeValue];
    
    //设置弹出框
    AVQuery *query = [AVQuery queryWithClassName:@"Remind"];
    [query whereKey:@"Type" equalTo:type.timeType];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
       
       
        
        [self setUpSettings:[objects[0] valueForKey:@"one"] :[objects[0] valueForKey:@"two"] :[objects[0] valueForKey:@"three"]threeTomgs:[objects[0] valueForKey:@"four"] fourTomgs:[objects[0] valueForKey:@"five"] five:[objects[0] valueForKey:@"six"] sevenTomge:[objects[0] valueForKey:@"seven"] eightTomge:[objects[0] valueForKey:@"six"] oneTime:@"04:40" twotime:@"04:00" threeTime:@"03:50" fourTime:@"03:00" fiveTime:@"02:20" evenTime:@"02:00" eightTime:@"01:20"];
        
    }];
    
   
    
    
//    
//    _float_totalDur+=COUNT_DUR_TIMER_INTERVAL;
//    
//    NSLog(@"%lf ----  %lf",_float_totalDur,self.progressView.progress);
//    
//    self.progressView.progress = _float_totalDur/MAX_VIDEO_DUR;
//    NSLog(@"%f",_float_totalDur);
//    if ([self.timeLabel.text isEqualToString:@""])
//    {
//    
//    _sureBtn.userInteractionEnabled = YES;
//    [_sureBtn setTitle:@"可以点了"  forState:UIControlStateNormal];
//}
//    if(self.progressView.progress==1)
//    {
//        [self touchUp];
//        [self performSelector:@selector(sureBtnClick) withObject:nil afterDelay:1];
//        
//    }
//    
    
}
- (void)stopCountDurTimer
{
    [self.timer invalidate];
    self.timer = nil;
}

#pragma mark - AVCaptureFileOutputRecordignDelegate
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didStartRecordingToOutputFileAtURL:(NSURL *)fileURL fromConnections:(NSArray *)connections
{
    [self startCountDurTimer];
   
    
    //    self.currentFileURL = fileURL;
    //
    //    self.currentVideoDur = 0.0f;
    //    [self startCountDurTimer];
    //
    //    if ([_delegate respondsToSelector:@selector(videoRecorder:didStartRecordingToOutPutFileAtURL:)]) {
    //        [_delegate videoRecorder:self didStartRecordingToOutPutFileAtURL:fileURL];
    //    }
}
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo: (void *)contextInfo {
    
    NSLog(@"-------&-------%@",videoPath);
    
    NSLog(@"&&&error:%@",error);
    
}
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error
{
    
    NSLog(@"didFinishRecordingToOutputFileAtURL---%lf",_float_totalDur);
//        self.totalVideoDur += _currentVideoDur;
//        NSLog(@"本段视频长度: %f", _currentVideoDur);
//        NSLog(@"现在的视频总长度: %f", _totalVideoDur);
//
//        if (!error) {
//            SBVideoData *data = [[SBVideoData alloc] init];
//            data.duration = _currentVideoDur;
//            data.fileURL = outputFileURL;
//    
//            [_videoFileDataArray addObject:data];
//        }
//    
//        if ([_delegate respondsToSelector:@selector(videoRecorder:didFinishRecordingToOutPutFileAtURL:duration:totalDur:error:)]) {
//            [_delegate videoRecorder:self didFinishRecordingToOutPutFileAtURL:outputFileURL duration:_currentVideoDur totalDur:_totalVideoDur error:error];
//        }
}
//- (UIStatusBarStyle)preferredStatusBarStyle
//{
//    return UIStatusBarStyleLightContent;
//}


- (UIButton *)buildButton:(CGRect)frame normalimgStr:(NSString *)normalImgStr highlightImgSrt:(NSString *)highightImgStr selectedImgStr:(NSString *)selectedImgStr parentView:(UIView *)parentView
{
    //设置按钮的格式
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    //设置按钮的大小
    btn.frame = frame;
    
    if (normalImgStr.length > 0) {
        //普通状态
        [btn setImage:[UIImage imageNamed:normalImgStr] forState:UIControlStateNormal];
    }
    if (highightImgStr.length > 0) {
        //点击时候的状态
        [btn setImage:[UIImage imageNamed:highightImgStr] forState:UIControlStateHighlighted];
        
    }
    if (selectedImgStr.length > 0) {
        //按住的状态
        [btn setImage:[UIImage imageNamed:selectedImgStr] forState:UIControlStateSelected];
    }
    //将你的But添加到你的Vire上
    [parentView addSubview:btn];
    return  btn;
    
}

//弹出框设置
- (void)setUpSettings:(NSString *)oneTomgs :(NSString *)twoTomgs  :(NSString *)twoTomge threeTomgs:(NSString *)three fourTomgs:(NSString *)fourTomgs  five:(NSString *)fouTomgs sevenTomge:(NSString *)seven eightTomge:(NSString *)eight oneTime:(NSString *)oneTime    twotime:(NSString *)twotime threeTime:(NSString *)threeTime  fourTime:(NSString *)fourTime fiveTime:(NSString *)fiveTime  evenTime:(NSString *)evenTime   eightTime:(NSString *)eightTime
{
    
    
    typeValue *type = [typeValue TimeTypeValue];
    

    if ([self.timeLabel.timeLabel.text isEqualToString:oneTime] != 0)
    {
        
        TAlertView *alert = [[TAlertView alloc] initWithTitle:[self Determine]
                                                   andMessage:oneTomgs];
        alert.timeToClose = 5;
        alert.buttonsAlign = TAlertViewButtonsAlignHorizontal;
        alert.style = TAlertViewStyleInformation;
        [alert showAsMessage];
        

        
    }else  if ([self.timeLabel.timeLabel.text isEqualToString:twotime] != 0)
    {
      
        TAlertView *alert = [[TAlertView alloc] initWithTitle:[self Determine]
                                                   andMessage:twotime];
        alert.timeToClose = 5;
        alert.buttonsAlign = TAlertViewButtonsAlignHorizontal;
        alert.style = TAlertViewStyleInformation;
        [alert showAsMessage];
        
        
        
        
        
    }else  if ([self.timeLabel.timeLabel.text isEqualToString:threeTime] != 0)
    {
        
        TAlertView *alert = [[TAlertView alloc] initWithTitle:[self Determine]
                                                   andMessage:three];
        alert.timeToClose = 5;
        alert.buttonsAlign = TAlertViewButtonsAlignHorizontal;
        alert.style = TAlertViewStyleInformation;
        [alert showAsMessage];
        
        
    }else  if ([self.timeLabel.timeLabel.text isEqualToString:fourTime] != 0)
    {
        TAlertView *alert = [[TAlertView alloc] initWithTitle:type.timeType
                                                   andMessage:fourTomgs];
        alert.timeToClose = 5;
        alert.buttonsAlign = TAlertViewButtonsAlignHorizontal;
        alert.style = TAlertViewStyleInformation;
        [alert showAsMessage];
        
        
    }else  if ([self.timeLabel.timeLabel.text isEqualToString:fiveTime] != 0)
    {
        TAlertView *alert = [[TAlertView alloc] initWithTitle:[self Determine]
                                                   andMessage:fouTomgs];
        alert.timeToClose = 5;
        alert.buttonsAlign = TAlertViewButtonsAlignHorizontal;
        alert.style = TAlertViewStyleInformation;
        [alert showAsMessage];
        
        
    }else  if ([self.timeLabel.timeLabel.text isEqualToString:evenTime] != 0)
    {
        
        TAlertView *alert = [[TAlertView alloc] initWithTitle:[self Determine]                                                  andMessage:seven];
        alert.timeToClose = 5;
        alert.buttonsAlign = TAlertViewButtonsAlignHorizontal;
        alert.style = TAlertViewStyleInformation;
        [alert showAsMessage];
        
    }else  if ([self.timeLabel.timeLabel.text isEqualToString:eightTime] != 0)
    {
        
        TAlertView *alert = [[TAlertView alloc] initWithTitle:[self Determine]                                                   andMessage:eight];
        alert.timeToClose = 5;
        alert.buttonsAlign = TAlertViewButtonsAlignHorizontal;
        alert.style = TAlertViewStyleInformation;
        [alert showAsMessage];
        
    
    }

}

- (NSString *)Determine
{
    NSString *temp = [[NSString alloc] init];
    typeValue *type = [typeValue  TimeTypeValue];
    if ([type.timeType isEqualToString:@"Love"] != 0)
    {
        if (type.manTO == YES)
        {
            //女士
            temp = type.oneText;
            
            
        }else if (type.manTO == NO)
        {
          //男士
         temp = type.twoText;
   
        
        }
}


    return temp;




}








- (BOOL)prefersStatusBarHidden//for iOS7.0
{
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
